//
//  HMSearchResultController.m
//  HMMeituanHD
//
//  Created by apple on 2017/5/19.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMSearchResultController.h"
#import "HMHomeViewController.h"
#import "HMCityModel.h"

@interface HMSearchResultController ()<UITableViewDelegate>
//查询结果集
@property (nonatomic, strong) NSMutableArray <HMCityModel *> *searchResults;

@end

@implementation HMSearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (void)fetchKeyword:(NSString *)keyword{
    //每次要重新查询,需要清空结果集
    self.searchResults = nil;
    //转为小写
    keyword = [keyword lowercaseString];
    
    //获取cities.plist中的数据 从homeVc中取出内存缓存即可
    HMHomeViewController *homeVc = [UIApplication sharedApplication].keyWindow.rootViewController.childViewControllers[0];
    
    //遍历每个城市的数据
    for (HMCityModel *city in homeVc.cities) {
        
        //匹配符合的城市名&城市名全拼&城市名拼音首字母
        if ([city.name containsString:keyword] || [city.pinYin containsString:keyword] || [city.pinYinHead containsString:keyword]) {
            //将匹配的城市展示在界面上
            [self.searchResults addObject:city];
        }
    }
    //刷新数据
    [self.tableView reloadData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

//显示组头
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    return [NSString stringWithFormat:@"共有%zd个结果", self.searchResults.count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.searchResults.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    //设置数据
    cell.textLabel.text = self.searchResults[indexPath.row].name;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    //发送城市切换通知
    [HMNoteCenter postNotificationName:HMCityDidChangeNote object:nil userInfo:@{HMCityDidChangeNoteCityName: self.searchResults[indexPath.row].name}];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 懒加载

- (NSMutableArray<HMCityModel *> *)searchResults{
    if (_searchResults == nil) {
        _searchResults = [[NSMutableArray alloc] init];
    }
    return _searchResults;
}


@end
